Python Control Flow & Loops Tutorial (2026)


In Python programming, control flow determines the order in which individual statements, instructions, or function calls are executed. Without control flow, programs would simply run line by line from top to bottom with no decision-making capability. Control flow statements give your code the power to make decisions, repeat tasks, and respond to different conditions.

In this comprehensive guide, we'll explore everything about Python control flow including conditional statements (if, elif, else), loops (for, while), loop control statements (break, continue, pass), the loop else clause, nested structures, list comprehensions, best practices, and common mistakes.

๐Ÿ”น What is Control Flow?

Control flow is the order in which a program's code executes. By default, Python executes code sequentially (line by line from top to bottom). Control flow statements allow you to alter this order based on conditions or to repeat blocks of code.

๐Ÿง  Think of control flow like traffic signals:

  • if/else = "If the light is green, go. Else, stop."
  • loops = "Drive around the block until you find parking."
  • break = "Exit the highway immediately."

๐Ÿ”น Indentation: The Foundation of Python Control Flow

Unlike other languages that use curly braces {}, Python uses indentation (whitespace) to define blocks of code. This is mandatory and makes Python code exceptionally readable.

# Correct indentation (4 spaces is standard)
if 5 > 2:
    print("Five is greater than two!")  # This line is indented
    print("This is also part of the if block")
print("This is outside the if block")  # Back to no indent

# Output:
# Five is greater than two!
# This is also part of the if block
# This is outside the if block

# Wrong - This will cause IndentationError
if 5 > 2:
print("Missing indent!")  # IndentationError: expected an indented block

⚠️ Indentation Rules

  • Use 4 spaces per indentation level (PEP 8 standard)
  • Never mix tabs and spaces
  • All statements in the same block must have identical indentation

๐Ÿ”น Conditional Statements: Making Decisions

Conditional statements allow your program to execute different code blocks based on whether a condition is True or False.

1️⃣ The if Statement

The simplest form of decision-making. The code block executes only if the condition evaluates to True.

# Basic if statement
temperature = 35

if temperature > 30:
    print("It's a hot day!")
    print("Drink plenty of water.")

print("Enjoy your day!")  # This always executes

# Output:
# It's a hot day!
# Drink plenty of water.
# Enjoy your day!

2️⃣ The if-else Statement

Provides an alternative path when the condition is False.

# if-else example
age = 16

if age >= 18:
    print("You are eligible to vote.")
else:
    print("You are not eligible to vote yet.")
    print(f"Come back in {18 - age} years.")

# Output:
# You are not eligible to vote yet.
# Come back in 2 years.

3️⃣ The if-elif-else Ladder

When you need to check multiple conditions sequentially. The first True condition executes, and the rest are skipped.

# Grade calculator using if-elif-else
score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 70:
    grade = "C"
elif score >= 60:
    grade = "D"
else:
    grade = "F"

print(f"Score: {score}, Grade: {grade}")

# Output:
# Score: 85, Grade: B

4️⃣ Nested if Statements

An if statement inside another if statement. Useful for checking additional conditions after a primary condition is met.

# Nested if - Movie ticket booking
age = 25
has_id = True

if age >= 18:
    if has_id:
        print("You can watch the R-rated movie.")
    else:
        print("You need an ID to verify your age.")
else:
    print("You are too young for this movie.")

# Output:
# You can watch the R-rated movie.

5️⃣ Ternary Operator (Conditional Expression)

A one-line shortcut for simple if-else assignments. Syntax: value_if_true if condition else value_if_false

# Traditional if-else
age = 20
if age >= 18:
    status = "Adult"
else:
    status = "Minor"
print(status)
# Output: Adult

# Ternary operator (one-liner)
status = "Adult" if age >= 18 else "Minor"
print(status)
# Output: Adult

# Another example
num = 10
result = "Even" if num % 2 == 0 else "Odd"
print(result)
# Output: Even

๐Ÿ”น Loops: Repeating Code Efficiently

Loops allow you to execute a block of code multiple times without writing it repeatedly. Python provides two main types: for loops and while loops.

1️⃣ The for Loop

Used to iterate over a sequence (list, tuple, string, dictionary, set, or range). It executes the block once for each item in the sequence.

# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# Output:
# I like apple
# I like banana
# I like cherry

# Iterating over a string
for char in "Python":
    print(char, end=" ")
# Output: P y t h o n 

# Iterating over a dictionary
student = {"name": "John", "age": 20, "grade": "A"}
for key, value in student.items():
    print(f"{key}: {value}")
# Output:
# name: John
# age: 20
# grade: A

2️⃣ The range() Function

Generates a sequence of numbers. Essential for loops that need to run a specific number of times.

Syntax Description Example
range(stop)0 to stop-1range(5) → 0,1,2,3,4
range(start, stop)start to stop-1range(2, 6) → 2,3,4,5
range(start, stop, step)start to stop-1 with steprange(1, 10, 2) → 1,3,5,7,9
# range() examples
print("Counting to 5:")
for i in range(1, 6):
    print(i, end=" ")
print() # New line
# Output: 1 2 3 4 5

print("Even numbers:")
for i in range(2, 11, 2):
    print(i, end=" ")
print() # New line
# Output: 2 4 6 8 10

print("Countdown:")
for i in range(5, 0, -1):
    print(i, end=" ")
print() # New line
# Output: 5 4 3 2 1

# Sum of first 100 numbers
total = sum(range(1, 101))
print(f"Sum of 1 to 100: {total}")
# Output: Sum of 1 to 100: 5050

3️⃣ The while Loop

Executes a block of code as long as a condition remains True. Useful when you don't know in advance how many iterations are needed.

# Basic while loop - Countdown
count = 5
while count > 0:
    print(count)
    count -= 1  # Decrement (crucial to avoid infinite loop)
print("Blast off!")

# Output:
# 5
# 4
# 3
# 2
# 1
# Blast off!

4️⃣ Infinite Loops (and How to Avoid Them)

An infinite loop occurs when the loop condition never becomes False. This can crash your program or freeze your computer.

⚠️ Infinite Loop Example (DO NOT RUN)

# This will run forever!
x = 1
while x > 0:  # x is always 1, condition never changes
    print("Help! I'm stuck!")
# Output (infinite):
# Help! I'm stuck!
# Help! I'm stuck!
# ... (continues forever)

✅ Safe version: Always include a way to exit the loop.

x = 5
while x > 0:
    print(f"x is {x}")
    x -= 1  # Condition will eventually become False
# Output:
# x is 5
# x is 4
# x is 3
# x is 2
# x is 1

๐Ÿ”น Loop Control Statements

These statements alter the normal flow of a loop, giving you fine-grained control over execution.

1️⃣ break Statement

Immediately terminates the loop entirely, even if the loop condition is still True.

# break example - Find first even number
numbers = [1, 3, 5, 8, 9, 12, 15]

for num in numbers:
    if num % 2 == 0:
        print(f"First even number found: {num}")
        break  # Exit loop immediately
    print(f"Checking {num}...")

# Output:
# Checking 1...
# Checking 3...
# Checking 5...
# First even number found: 8

# break in while loop
i = 0
while True:  # Infinite loop pattern
    print(i)
    i += 1
    if i == 5:
        break  # Exit after 5 iterations
# Output:
# 0
# 1
# 2
# 3
# 4

2️⃣ continue Statement

Skips the rest of the current iteration and jumps to the next iteration of the loop.

# continue example - Print only odd numbers
for num in range(1, 11):
    if num % 2 == 0:
        continue  # Skip even numbers
    print(num, end=" ")
# Output: 1 3 5 7 9 

# continue with string processing
message = "Hello World!"
vowels = "aeiouAEIOU"

for char in message:
    if char in vowels:
        continue  # Skip vowels
    print(char, end="")
# Output: Hll Wrld!

3️⃣ pass Statement

A null operation — it does nothing. Used as a placeholder when syntax requires a statement but you don't want any code to execute.

# pass as placeholder
def my_function():
    pass  # TODO: Implement later

class MyClass:
    pass  # Empty class definition

# pass in conditional
x = 10
if x > 5:
    pass  # Do nothing for now
else:
    print("x is small")
# Output: (Nothing, because x > 5 and pass does nothing)

# pass in loop (rare but valid)
for i in range(5):
    if i == 2:
        pass  # Placeholder
    else:
        print(i)
# Output:
# 0
# 1
# 3
# 4
Statement Effect Use Case
breakExits the loop completelySearch found, error condition
continueSkips to next iterationFilter out unwanted items
passDoes nothingPlaceholder for future code

๐Ÿ”น The Loop else Clause (Python's Unique Feature)

Python allows an else block after a for or while loop. The else block executes only if the loop completes normally (without encountering a break statement).

# Loop else - Search for a prime number
def is_prime(n):
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            print(f"{n} is divisible by {i}")
            break  # Found a divisor
    else:
        # This runs ONLY if break was NOT encountered
        print(f"{n} is prime!")
        return True
    return False

is_prime(17)
# Output: 17 is prime!

is_prime(21)
# Output: 21 is divisible by 3

๐Ÿ’ก Pro Tip: The loop else clause is perfect for search operations where you need to know if something was not found.

๐Ÿ”น Nested Loops

A loop inside another loop. The inner loop completes all its iterations for each iteration of the outer loop.

# Multiplication table (1-3) - Shortened for display
print("Multiplication Table (1-3):")
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j:2}", end="  ")
    print()  # New line after each row

# Output:
# Multiplication Table (1-3):
# 1 x 1 =  1  1 x 2 =  2  1 x 3 =  3  
# 2 x 1 =  2  2 x 2 =  4  2 x 3 =  6  
# 3 x 1 =  3  3 x 2 =  6  3 x 3 =  9  

# Pattern printing - Right triangle
print("Pattern:")
for i in range(1, 6):
    for j in range(i):
        print("*", end="")
    print()

# Output:
# *
# **
# ***
# ****
# *****

๐Ÿ”น List Comprehension (Pythonic Looping)

A concise way to create lists using a single line of code. It's faster and more readable than traditional loops for simple transformations.

# Traditional for loop
squares = []
for i in range(1, 6):
    squares.append(i ** 2)
print(squares)
# Output: [1, 4, 9, 16, 25]

# List comprehension (same result, one line)
squares = [i ** 2 for i in range(1, 6)]
print(squares)
# Output: [1, 4, 9, 16, 25]

# With condition (filtering)
even_squares = [i ** 2 for i in range(1, 11) if i % 2 == 0]
print(even_squares)
# Output: [4, 16, 36, 64, 100]

# Nested list comprehension
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
# Output: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

# Dictionary comprehension
squares_dict = {i: i ** 2 for i in range(1, 6)}
print(squares_dict)
# Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

๐Ÿ”น Real-World Example: Simple Number Guessing Game

This example combines while loops, break, continue, and nested conditions in a practical scenario.

import random

def guessing_game():
    secret_number = random.randint(1, 20)
    attempts = 0
    max_attempts = 5
    
    print("=== Number Guessing Game ===")
    print("I'm thinking of a number between 1 and 20.")
    
    while attempts < max_attempts:
        try:
            guess = int(input(f"Attempt {attempts + 1}/{max_attempts}. Take a guess: "))
        except ValueError:
            print("Invalid input! Please enter a number.")
            continue  # Skip rest of loop, don't count as attempt
        
        attempts += 1
        
        if guess < 1 or guess > 20:
            print("Guess must be between 1 and 20!")
            continue
        elif guess < secret_number:
            print("Too low!")
        elif guess > secret_number:
            print("Too high!")
        else:
            print(f"Correct! You guessed it in {attempts} attempts!")
            break  # Exit loop on correct guess
    else:
        # Loop else - executes if loop completes without break
        print(f"Out of attempts! The number was {secret_number}.")

# Uncomment to play
# guessing_game()

# Sample Run Output:
# === Number Guessing Game ===
# I'm thinking of a number between 1 and 20.
# Attempt 1/5. Take a guess: 10
# Too low!
# Attempt 2/5. Take a guess: 15
# Too high!
# Attempt 3/5. Take a guess: 12
# Correct! You guessed it in 3 attempts!

๐Ÿ”น Common Mistakes and How to Avoid Them

❌ Mistake 1: Forgetting the Colon (:)

# Wrong - SyntaxError
x = 5
if x > 5
    print("x is large")

# Correct
if x > 5:
    print("x is large")
# Output: (Nothing, since x=5 is not > 5)

❌ Mistake 2: Infinite while Loop

# Wrong - Infinite loop
count = 0
while count < 5:
    print(count)
    # Forgot count += 1
# Output (infinite): 0 0 0 0 0 ...

# Correct
count = 0
while count < 5:
    print(count)
    count += 1  # Increment to eventually exit
# Output: 0 1 2 3 4

❌ Mistake 3: Modifying a List While Iterating

# Wrong - Unexpected behavior
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # Modifying while iterating!
print(numbers)
# Output: [1, 3, 5] (Seems to work but unreliable. Avoid!)

# Correct - Create a new list
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0]
print(numbers)
# Output: [1, 3, 5]

❌ Mistake 4: Using = Instead of == in Conditions

# Wrong - Assignment in condition (SyntaxError)
x = 10
if x = 10:  # SyntaxError: invalid syntax
    print("Yes")

# Correct
if x == 10:  # Comparison
    print("Yes")
# Output: Yes

❌ Mistake 5: Misunderstanding range() Boundaries

# range(1, 5) generates 1,2,3,4 (NOT 5)
for i in range(1, 5):
    print(i)
# Output: 1 2 3 4

# To include 5, use range(1, 6)
for i in range(1, 6):
    print(i)
# Output: 1 2 3 4 5

๐Ÿ”น Best Practices for Clean Control Flow

  • Keep conditions simple – If a condition is complex, break it into variables.
  • Avoid deep nesting – If you have more than 3 levels of nesting, refactor into functions.
  • Use meaningful variable namesfor student in students not for s in students
  • Prefer for loops over while loops when iterating over known sequences.
  • Use enumerate() instead of range(len()) when you need both index and value.
  • Use list comprehensions for simple transformations and filtering.
  • Add comments for non-obvious loop logic.
# Better: Use enumerate() instead of range(len())
fruits = ["apple", "banana", "cherry"]

# Avoid this
for i in range(len(fruits)):
    print(f"{i}: {fruits[i]}")
# Output:
# 0: apple
# 1: banana
# 2: cherry

# Preferred
for i, fruit in enumerate(fruits):
    print(f"{i}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry

๐Ÿ”น Quick Reference Cheat Sheet

Statement Syntax When to Use
ifif condition:Single condition check
if-elseif condition: ... else: ...Two-way branch
if-elif-elseif c1: ... elif c2: ... else: ...Multiple conditions
for loopfor item in sequence:Iterate over known sequence
while loopwhile condition:Unknown number of iterations
breakbreakExit loop immediately
continuecontinueSkip to next iteration
passpassPlaceholder (do nothing)
range()range(start, stop, step)Generate number sequence
enumerate()for i, val in enumerate(seq):Get index and value

๐Ÿงช Test Your Knowledge: Control Flow Challenge

What will be the output of this Python code? (Comment your answer below!)

result = 0
for i in range(1, 6):
    if i % 2 == 0:
        result += i
    else:
        result -= i
        
    if result > 0:
        continue
    else:
        result += 10

print(result)
๐Ÿ‘† Click to Reveal Answer & Explanation

Answer: 12

Step-by-step trace:
i=1: result=-1 → result<=0 → result=9
i=2: result=11 → result>0 → continue (skip +10)
i=3: result=8 → result>0 → continue
i=4: result=12 → result>0 → continue
i=5: result=7 → result>0 → continue
Final result: 12

๐Ÿ”น Frequently Asked Questions (FAQ)

Q1: What is the difference between for and while loops?
✅ Use for when you know how many times to iterate (or iterating over a sequence). Use while when you don't know in advance and depend on a condition.

Q2: Can I use else with loops in Python?
✅ Yes! The else block after a loop executes only if the loop completes normally (without encountering break).

Q3: What does break do inside nested loops?
break only exits the innermost loop that contains it. It does not affect outer loops.

Q4: How do I exit multiple nested loops at once?
✅ Use a flag variable, raise an exception, or encapsulate the nested loops in a function and use return.

Q5: What is the difference between pass and continue?
pass does nothing (placeholder). continue skips the rest of the current iteration and moves to the next.

Q6: Is list comprehension faster than a for loop?
✅ Yes, list comprehensions are optimized in C and generally execute faster than equivalent for loops with .append().

Q7: Can I have an empty if statement?
✅ Yes, use pass as a placeholder: if condition: pass

๐Ÿ”น Conclusion

Mastering control flow and loops is essential for writing efficient Python programs. From simple if-else decisions to complex nested loops with break and continue, these constructs give you the power to control exactly how your code executes. Remember the golden rules: indentation defines blocks, conditions must evaluate to Boolean, and always provide a way to exit your while loops. Practice these concepts with real-world problems, and soon you'll be writing Python code that's both powerful and elegant.

Popular posts from this blog

Windows Registry Forensics: Detecting Malware Persistence with Process Monitor

Mastering Incident Response: Complete Guide to CrowdResponse Forensic Tool